package com.ruoyi.web.controller.util;


import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;

/**
 * 每个用户一个目录保存文件, 以md5为文件名保存文件避免用户上传重复文件
 *
 * @author ChenPantao
 * @date 2017年12月15日
 */

public class OssUtil {

    public static String getIMGS(MultipartFile[] IMG_imgs , Long userid, String bucketName){
        String imgs = "";
        for(int i = 0 ;i<IMG_imgs.length ; i++){
            String img = uploadFile(IMG_imgs[i], userid, bucketName);
            if(i<IMG_imgs.length-1){
                imgs = imgs + img + ",";
            }else{
                imgs = imgs + img;
            }
        }
        return imgs;
    }

    public static synchronized String uploadFile(MultipartFile uploadFile, Long userid, String bucketName) {
        try {
            byte[] bytes = getBytes(uploadFile.getInputStream());
            String degist = getDegist(bytes);
            for(int i = degist.length() ; i < 32 ; i++){
                degist = "0" + degist;
            }
            String fileName = uploadFile.getOriginalFilename();
            Integer index = fileName.lastIndexOf(".");

            String fileExtension = "";
            if(index != -1){
                fileExtension = fileName.substring(fileName.lastIndexOf("."));
            }
            fileName = degist + fileExtension;
            Long fileSize = 0L + bytes.length;
            String diskName = userid + "/";
            String OSS = Oss.uploadObject2OSS(new ByteArrayInputStream(bytes), fileName, fileSize, bucketName,
                    diskName);
            if (fileName.equalsIgnoreCase(OSS + fileExtension)) {
                return diskName + fileName;
            } else {
                throw new RuntimeException("fail to upload file , ");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("fail to upload file");
        }
    }

    public static String getDegist(byte[] bytes) throws Exception {
        MessageDigest messagedigest = MessageDigest.getInstance("MD5");
        messagedigest.update(bytes);
        String md5 = new BigInteger(1, messagedigest.digest()).toString(16);
        return md5;
    }

    public static byte[] getBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
        byte[] b = new byte[4096];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        byte[] ret = out.toByteArray();
        in.close();
        out.close();
        return ret;
    }

}
